import org.jsecurity.SecurityUtils

class SecurityFilters {
	
	
	/**
	 * Called when an unauthenticated user trys to access a secured
	 * page.
	 */
	def onNotAuthenticated(subject, d) {
		
		def targetUri = d.request.forwardURI 
		if (d.request.queryString) {
			targetUri = "${targetUri}?${d.request.queryString}"
		}
		
		//Work around for submitting the credentials
		//Without this condition the user cannot signin
		//He will be redirected to login at each attempt
		if (!targetUri.contains('signin')) {
			// Redirect to login page.
			d.redirect(controller: 'login', action: 'index', params:[originalURI: targetUri])
			return
		}
	}	
	
	static filters = {
		// Ensure that all controllers and actions require an authenticated user,
		
		// All of the task related actions require authetication
		displaytask(controller:"task", action:"(create|save|list|show)") {
			before = {
				accessControl()
			}
		}
		
		// Only the show account action requires authetication
		displayAccount(controller:"account", action:"(show)") {
			before = {
				accessControl()
			}
		}
		
		accountInSession(controller:"*", action:"*") {
			before = {
				def subject = SecurityUtils.getSubject() 
				if(subject && subject?.principal) {
					session.account = Account.findByUsername(subject.principal)						
				}
			}
		}
	}
}